<template>

  <!-- 列表 -->
  <div>

    <el-container class="layout-container">
      <el-aside class="left" :style="{ width: leftWidth + 'px' }">
        <el-input v-model="filterText" style="width: 220px" placeholder="Filter keyword">
          <template #append>
            <el-button @click="toggleExpandAll">
              <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-sorting" />
              </svg>

            </el-button>
          </template>
        </el-input>


        <el-tree ref="treeRef" v-loading="loading" :data="list" draggable node-key="id" @node-drag-end="handleDragEnd"
          :filter-node-method="filterNode" @node-click="handleNodeClick" :stripe="true" :show-overflow-tooltip="true"
          row-key="id" :props="treeProps" :default-expand-all="isExpandAll" v-if="refreshTable" />

      </el-aside>
      <div class="resize" @mousedown="startDrag"></div>



      <el-container v-show="preview" class="layout-container">
        <el-container class="right editor-right" v-loading="cmpLoading" :style="{ width: rightWidth + 'px' }">
          <el-header>
            <div class="toolbar">
              <el-form :model="queryParams" ref="queryFormRef" :inline="true">
                <el-form-item>
                  <el-button v-show="preview" @click="preview = false">编辑</el-button>

                </el-form-item>
              </el-form>
            </div>
          </el-header>

          <el-main>

            <!-- 加载状态提示 -->
            <div v-if="cmpLoading">

              <template>
                <el-table v-loading="cmpLoading" style="width: 100%">
                  <el-table-column prop="date" label=" "  />
                </el-table>
              </template>

            </div>

            <!-- 错误提示 -->
            <div v-if="error" class="error">加载失败，请重试</div>

            <!-- 动态渲染加载后的组件 -->
            <component :is="asyncComponent" v-if="asyncComponent && !cmpLoading" />

          </el-main>

        </el-container>
      </el-container>


      <el-container v-show="!preview" class="right editor-right" :style="{ width: rightWidth + 'px' }">
        <el-header>
          <div class="toolbar">

            <!-- 搜索工作栏 -->
            <el-form :model="queryParams" ref="queryFormRef" :inline="true">
              <el-form-item>
                <el-button v-show="!preview" @click="preview = true">预览</el-button>

              </el-form-item>

              <el-form-item>
                <el-input v-model="currentNodeDataRef.name" placeholder="">


                  <template #append>

                    <el-button type="primary" plain @click="openForm('create', 0)"
                      v-hasPermi="['infra:demo02-category:create']">
                      <Icon icon="ep:folder-add" class="mr-5px" />

                    </el-button>

                    <el-button type="primary" plain @click="openForm('create', 1)"
                      v-hasPermi="['infra:demo02-category:create']">
                      <Icon icon="ep:document-add" class="mr-5px" />
                    </el-button>

                    <el-button @click="handleQuery">
                      <Icon icon="ep:refresh" class="mr-5px" />
                    </el-button>

                    <el-button @click="handleSave">
                      <Icon icon="fa:save" class="mr-5px" />
                    </el-button>
                  </template>

                </el-input>
              </el-form-item>


            </el-form>
          </div>
        </el-header>
        <el-main>
          <div id="monaco-editor-container" style=" height: 100%; border: 1px solid grey"></div>

        </el-main>
      </el-container>
    </el-container>

    <el-dialog v-model="dialogFormVisible" title="编译错误" label-position="top" width="500">
      <el-form :model="form">
        <label>{{ form.title }}</label>
        <el-form-item label="">
          <el-input v-model="form.message" :autosize="{ minRows: 2, maxRows: 10 }" type="textarea" autocomplete="off" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Close</el-button>
        </div>
      </template>
    </el-dialog>

      <!-- 表单弹窗：添加/修改 -->
  <Demo02CategoryForm ref="formRef" @success="getList" />

  </div>


</template>

<script setup lang="ts">
import { handleTree } from '@/utils/tree'
import * as Demo02CategoryApi from '@/api/infra/demo/demo02'
import Demo02CategoryForm from './Demo02CategoryForm.vue'
import { ref, watch } from 'vue'
import { ElTree } from 'element-plus'
import { compileCode } from "@/views/infra/codegen/sfc/sfc-compiler.js"
import { loadSvg } from '@/utils/svg'

const preview = ref(false)

const dialogFormVisible = ref(false)
const form = reactive({
  title: '',
  message: '',
});

loadSvg(`
<symbol id="icon-sorting" viewBox="0 0 1024 1024">
<path d="M673.158095 252.830476v634.026667h-71.923809V172.251429c0-10.142476 4.022857-19.846095 11.215238-26.989715a38.546286 38.546286 0 0 1 54.296381 0L926.47619 403.553524l-50.883047 50.566095-202.435048-201.289143zM350.841905 768.121905V134.095238h71.923809v719.823238l-0.902095 6.460953c-1.26781 8.045714-2.56 9.728-9.703619 18.992761l-8.045714 4.388572c-17.92 9.45981-20.577524 7.996952-43.154286-4.388572L97.52381 617.374476l50.883047-50.541714 202.435048 201.264762z" p-id="8439"></path>
</symbol>
`);


defineOptions({ name: 'Demo02Category' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const cmpLoading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const queryParams = reactive({
  name: null,
  pid: null,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

let editor = null;

const treeProps = {
  label: 'name'      // 使用 title 字段作为 label

};

const currentNodeDataRef = ref({
  name: "",
  compileJs: "",
  compileCss: "",
  type: 0,
  id: "",
  pid: "",
  sourceCode: "" // 初始化为空字符串

})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    console.log('queryParams ==== > ', queryParams)
    const data = await Demo02CategoryApi.getCmpPage(queryParams)
    list.value = handleTree(data.list, 'id', 'pid')
  } finally {
    loading.value = false
  }
}


const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()


watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}

const getParamsFromHash = (hashPart) => {

  const queryParams = {};

  // 找到第一个 ? 符号的位置
  const questionIndex = hashPart.indexOf('?');

  if (questionIndex == -1) {
    return queryParams;
  }
  // 提取 ? 后面的查询字符串
  const queryString = hashPart.substring(questionIndex + 1);

  // 创建一个对象来存储查询参数

  // 解析查询字符串
  new URLSearchParams(queryString).forEach((value, key) => {
    queryParams[key] = value;
  });

  return queryParams;
}

const handleNodeClick = async (data, node) => {
  console.log('节点被点击:', data);
  console.log('节点组件:', node);
  const res = await Demo02CategoryApi.getCmp(data.id)
  currentNodeDataRef.value = res;



  const cmpName = res.name;
  loadComponentByName(cmpName);
  saveCmpId(data.id);

};

const saveCmpId = (cmpId: string) => {
    window.localStorage.setItem("_cmpId", cmpId);
};


const handleDragEnd = async (
  draggingNode: Node,
  dropNode: Node,
  dropType: NodeDropType,
  ev: DragEvents
) => {
  console.log('tree drag end:', draggingNode && draggingNode.label, dropNode && dropNode.label, dropType)
  draggingNode.data.pid = dropNode?.data?.id;
  currentNodeDataRef.value = draggingNode.data;
  await Demo02CategoryApi.updateCmp(currentNodeDataRef.value)
  getList()

}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const handleSave = async () => {
  console.log('保存按钮被点击');
  dialogFormVisible.value = false;
  currentNodeDataRef.value.sourceCode = editor.getValue();
  try {
    if (currentNodeDataRef.value.sourceCode) {
      const { compileJs, compileCss } = compileCode(currentNodeDataRef.value.sourceCode)
      currentNodeDataRef.value.compileJs = compileJs;
      currentNodeDataRef.value.compileCss = compileCss;
    }

    dialogFormVisible.value = false;
  } catch (err) {
    dialogFormVisible.value = true;

    // message.error(err.message + " " +  err.stack)
    form.title = err.message;
    form.message = err.stack;
    //ElNotification.error({title: '编译失败', message: err.message + " " +  err.stack, duration: 0});
  }

  await Demo02CategoryApi.updateCmp(currentNodeDataRef.value)
  message.success('保存成功')

  await getList();

  loadComponentByName(currentNodeDataRef.value.name);

}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, cmpType: number, id?: string) => {
  formRef.value.open(type, cmpType, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await Demo02CategoryApi.deleteDemo02Category(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 展开/折叠操作 */
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const toggleExpandAll = async () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  await nextTick()
  refreshTable.value = true
}

/** 初始化 **/
onMounted(async () => {
  window.addEventListener('resize', () => {
    rightWidth.value = window.innerWidth - leftWidth.value - 10;
  });

  await new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = "/monaco-editor/vs/loader.js?t=11"; // 使用绝对路径
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });


  await loadEditor();

  await getList();

  const cmpId = window.localStorage.getItem("_cmpId");
  const res = await Demo02CategoryApi.getCmp(cmpId)
  currentNodeDataRef.value = res;
  setTimeout(() => {
    const cmpName = currentNodeDataRef.value.name;
    loadComponentByName(cmpName);
  }, 1000); // 延迟100毫秒执行

})

async function loadEditor(){

    const origin = window.location.origin;

    return new Promise((resolve,reject) => {
        require.config({ paths: { vs: origin + '/monaco-editor/vs' } });

        require(['vs/editor/editor.main'], function () {
          editor = monaco.editor.create(document.getElementById('monaco-editor-container'), {
            value: '',
            language: 'html'
          });

          resolve(1);
        });

    });
}

const leftWidth = ref(200); // 左侧宽度
const rightWidth = ref(window.innerWidth - 210); // 右侧宽度（总宽度 - 左侧宽度 - 拖动条宽度）

const startDrag = (e: MouseEvent) => {
  const startX = e.clientX;
  const initialLeftWidth = leftWidth.value;

  const handleMouseMove = (e: MouseEvent) => {
    const newLeftWidth = initialLeftWidth + (e.clientX - startX);
    if (newLeftWidth < 100) return; // 最小宽度限制
    leftWidth.value = newLeftWidth;
    rightWidth.value = window.innerWidth - newLeftWidth - 10; // 更新右侧宽度
  };

  const handleMouseUp = () => {
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);

    editor.layout();
  };

  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
};


import { defineAsyncComponent, onMounted } from 'vue';


const loadComponentByName = async (cmpName) => {
  const time = new Date().getTime();

  console.log("  #######  加载组件", cmpName)

  loadComponent("/admin-api/magic-cmp/script/" + cmpName + '?t=' + time, cmpName);

  if (currentNodeDataRef.value.sourceCode) {
    editor.setValue(currentNodeDataRef.value.sourceCode);
  } else {
    editor.setValue('');
  }

  setTimeout(() => {
    editor.focus();
  }, 100); // 延迟100毫秒执行

}


// 响应式变量
const asyncComponent = shallowRef(null); // 保存动态加载的组件
const error = ref(false);         // 错误状态

// 点击按钮触发加载
const loadComponent = async (url, cmpName) => {
  // if (asyncComponent.value) return; // 避免重复加载

  cmpLoading.value = true;
  error.value = false;

  try {
    // 动态插入 <script> 标签
    await new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = url; // 使用绝对路径
      script.onload = resolve;
      script.onerror = reject;
      document.head.appendChild(script);
    });
    if (!window.cmpFuncWrap) {
      window.cmpFuncWrap = {};
    }

    const MyComponent = window.cmpFuncWrap[cmpName]();

    // 假设 JS 文件将组件挂载到全局变量 window.MyComponent
    if (!MyComponent) {
      throw new Error('组件未正确导出');
    }

    // 将全局组件转换为 Vue 异步组件
    asyncComponent.value = defineAsyncComponent({
      loader: () => Promise.resolve(MyComponent),
      delay: 200,
      timeout: 3000
    });
  } catch (err) {
    error.value = true;
    console.error('加载失败:', err);
  } finally {
    cmpLoading.value = false;
  }


}



</script>
<style lang="css" scoped>

.el-header {
  background-color: var(--el-color-primary-light-7);
}

.layout-container {
  display: flex;
  width: 100%;
  height: 100vh;
}

.toolbar {
  padding: 8px;
}

.editor-right {
  padding: 8px;
}

.editor-right .el-header {
  margin: 0;
  height: auto;
}

.toolbar .el-form--inline .el-form-item {
  margin: 0;
}

.el-form--inline .el-form-item {
  margin: 0;
}

.left {
  overflow: hidden;
}

.resize {
  width: 10px;
  cursor: col-resize;
  background-color: #d6d6d6;
  user-select: none;
}

.right {
  flex-grow: 1;
  overflow: hidden;
  background: #fff;
}

.el-header {
  color: var(--el-text-color-primary);
}

.icon{
  height: 16px;
  width: 16px;
}
</style>